//
//  UIView+Extexsion.swift
//  SXSchool-Parent
//
//  Created by 苏州巨细 on 2018/7/13.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import Foundation

/// 加载xib快捷协议方法，需要xib和类同名
protocol NibLoadable { }
extension NibLoadable where Self : UIView {
    //在协议里面不允许定义class 只能定义static
    static func loadFromNib(_ nibname: String? = nil) -> Self {//Self (大写) 当前类对象
        //self(小写) 当前对象
        let loadName = nibname == nil ? "\(self)" : nibname!
        
        return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
    }
}


extension UIView: NibLoadable {
    
    
}

/// 关联属性 key
private var kUIViewTouchEventKey = "kUIViewTouchEventKey"

/// 点击事件闭包
public typealias UIViewTouchEvent = (AnyObject) -> ()

//给视图添加点击事件
extension UIView {
    
    private var touchEvent: UIViewTouchEvent? {
        
        set {
            objc_setAssociatedObject(self, &kUIViewTouchEventKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            if let event = objc_getAssociatedObject(self, &kUIViewTouchEventKey) as? UIViewTouchEvent {
                return event
            }
            return nil
        }
    }
    
    /// 添加点击事件
    ///
    /// - Parameter event: 闭包
    func addTouchEvent(event: @escaping UIViewTouchEvent) {
        
        self.touchEvent = event
        // 先判断当前是否有交互事件，如果没有的话。。。所有gesture的交互事件都会被添加进gestureRecognizers中
        if (self.gestureRecognizers == nil) {
            self.isUserInteractionEnabled = true
            // 添加单击事件
            let tapEvent = UITapGestureRecognizer.init(target: self, action: #selector(touchedAciton))
            self.addGestureRecognizer(tapEvent)
        }
    }
    
    /// 点击事件处理
    @objc private func touchedAciton() {
        guard let touchEvent = self.touchEvent else {
            return
        }
        touchEvent(self)
    }
}
